

//
//  CPJComposeView.swift
//  Sina
//
//  Created by YYY on 2017/8/24.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

import pop

class CPJComposeView: UIView {

    //滑动视图
    @IBOutlet weak var mainScrollView: UIScrollView!
    
    //关闭按钮水平约束
    @IBOutlet weak var closeButtonCenterXCons: NSLayoutConstraint!
    //返回按钮水平约束
    @IBOutlet weak var returnButtonCenterCons: NSLayoutConstraint!
    
    //返回按钮
    @IBOutlet weak var returnButton: UIButton!
    
    //完成回调
    private var completionBlock: ((_ clsName: String?)->())?
    
    fileprivate let buttonInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "ComposeViewController"],
                              ["imageName": "tabbar_compose_photo", "title": "照片／视频"],
                              ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                              ["imageName": "tabbar_compose_lbs", "title": "签到"],
                              ["imageName": "tabbar_compose_review", "title": "点评"],
                              ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                              ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                              ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                              ["imageName": "tabbar_compose_music", "title": "音乐"],
                              ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]
    //关闭视图
    @IBAction func closeAction()
    {
        //隐藏视图
        hideButtonsAnimation()
    }
    
    //返回事件
    @IBAction func returnAction()
    {
        let offset = CGPoint(x: 0, y: 0)
        mainScrollView.setContentOffset(offset, animated: true)
       
        closeButtonCenterXCons.constant = 0
        returnButtonCenterCons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnButton.alpha = 0
        }) { (_) in
            self.returnButton.isHidden = true
            self.returnButton.alpha = 1
        }
    }
    
    @objc func otherAction(selectButton: CPJComposeTypeButton)
    {
        //遍历当前视图
        //选中的按钮变大
        //未选中的按钮变小
        let page = Int(mainScrollView.contentOffset.x/mainScrollView.width)

        let buttonView = mainScrollView.subviews[page]
        
        for (i,btn) in buttonView.subviews.enumerated()
        {
            //缩放动画
            let scaleAnimation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            let scale = (btn == selectButton) ? 2 : 0.2
            //缩放比例
            scaleAnimation.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            //缩放持续时间
            scaleAnimation.duration = 0.5
            //添加动画到视图
            btn.pop_add(scaleAnimation, forKey: nil)
            
            //alpha动画
            let alphaAnimation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnimation.toValue = 0.2
            alphaAnimation.duration = 0.5
            btn.pop_add(alphaAnimation, forKey: nil)
            
            if i == 0
            {
                alphaAnimation.completionBlock = { _,_ in
                    
                    print("完成回调")
                    
                    
                    self.completionBlock?(selectButton.clsName)
                }
            }
            
        }
        
        //print(btn.clsName)
        //print()
        
    }
    //点击更多
    @objc func clickMore()
    {
        let point = CGPoint(x: kScreenWidth, y: 0)
        //设置滑动视图偏移
        mainScrollView.setContentOffset(point, animated: true)
        print("点我了")
        
        //显示返回按钮
        returnButton.isHidden = false
        //设置按钮水平偏移量
        returnButtonCenterCons.constant -= kScreenWidth/6
        closeButtonCenterXCons.constant += kScreenWidth/6
        
        //添加动画
        UIView.animate(withDuration: 0.33) {
            self.layoutIfNeeded()
        }
    }
    
    //类方法
    class func composeView() -> CPJComposeView
    {
        let nib = UINib(nibName: "CPJComposeView", bundle: nil)
        //xib默认大小是（600，600）
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! CPJComposeView
        view.frame = UIScreen.main.bounds
        view.setupUI()
        return view
        
    }

    //显示撰写视图
    func show(completeBlock: @escaping (_ classNameString: String?)->())
    {
        completionBlock = completeBlock
        
        guard let mainVC = UIApplication.shared.keyWindow?.rootViewController else
        {
            return
        }
        //添加到主控器上
        mainVC.view.addSubview(self)
        //显示动画
        showComposeViewAnimation()
    }
}

private extension CPJComposeView
{
    //显示当前视图动画
    func showComposeViewAnimation()
    {
        //创建动画
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        animation.fromValue = 0
        animation.toValue = 1
        animation.duration = 0.25
        //添加到视图
        pop_add(animation, forKey: nil)
        
        //添加按钮动画
        addButtonsAnimation()
    }
    //隐藏当前视图动画
    func hideComposeViewAnimation()
    {
        //创建动画
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        //设置动画属性
        animation.fromValue = 1
        animation.toValue = 0
        animation.duration = 0.25
        
        //添加到视图
        pop_add(animation, forKey: nil)
    }
    
    //添加按钮动画
    func addButtonsAnimation()
    {
        let view = mainScrollView.subviews[0]
        
        for (i,btn) in view.subviews.enumerated()
        {
            //创建动画
            let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //设置动画属性
            animation.fromValue = btn.center.y + 350
            animation.toValue = btn.center.y
        
            //弹力系数，取值范围[0,20]，数值越大，弹性越大，默认是4
            animation.springBounciness = 8
            
            //弹力速度，取值范围[0,20]，数值越大，速度越大，默认是12
            animation.springSpeed = 8
            
            //设置动画的开始时间
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            //添加动画
            btn.layer.pop_add(animation, forKey: nil)
        }
    }
    
    //隐藏按钮动画
    func hideButtonsAnimation()
    {
        //当前滑动视图滑动到第几页
        let page = Int(mainScrollView.contentOffset.x / mainScrollView.width)
        let buttonCurrentView = mainScrollView.subviews[page]
        for (i,btn) in buttonCurrentView.subviews.enumerated().reversed()
        {
            //创建动画
            let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            //设置动画属性
            animation.fromValue = btn.center.y
            animation.toValue = btn.center.y + 350
            
            //设置动画开始时间
            let index = buttonCurrentView.subviews.count - i
            
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(index) * 0.025
            //添加动画
            btn.layer.pop_add(animation, forKey: nil)
            
            if i == 0
            {
        
                animation.completionBlock = { (_,_)->() in
                    //隐藏当前视图动画
                    self.hideComposeViewAnimation()
                }
            }
        }
        
        
    }
}

private extension CPJComposeView
{
    func setupUI ()
    {
        //强制刷新布局
        layoutIfNeeded()
        
        let rect = mainScrollView.bounds
        for i in 0..<2
        {
            let view = UIView(frame: rect.offsetBy(dx: CGFloat(i) * kScreenWidth, dy: 0))
            //向视图中添加按钮
            addButtons(buttonView: view, flag: i*6)
            //添加视图到滑动视图
            mainScrollView.addSubview(view)
        }
        //设置滑动视图
        mainScrollView.showsVerticalScrollIndicator = false
        mainScrollView.showsHorizontalScrollIndicator = false
        mainScrollView.contentSize = CGSize(width: kScreenWidth * 2, height: 0)
        //取消弹性
        mainScrollView.bounces = false
        //禁止滚动
        //mainScrollView.isScrollEnabled = false
    }
    
    func addButtons(buttonView: UIView,flag: Int)
    {
        let count: Int = 6
  
        //添加六个按钮 按钮的索引从flag开始
        for i in flag..<(flag+count)
        {
            if i >= buttonInfo.count
            {
                //终止循环
                break
            }
            let dict  = buttonInfo[i]
            //图片 文字
            guard let imageName = dict["imageName"],
            let title = dict["title"] else
            {
                //跳出本次循环，继续下一层循环
                continue
            }
            //设置按钮
            let btn = CPJComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            buttonView.addSubview(btn)
            btn.clsName = dict["clsName"]
            
            if let actionName = dict["actionName"]
            {
                //通过Selector添加监听方法
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
                //btn.addTarget(self, action: #selector(clickMore), for: .touchUpInside)
            }
            else
            {
                //通过Selector添加监听方法
                btn.addTarget(self, action: #selector(otherAction), for: .touchUpInside)
            }
        }
        
        //六个按钮的布局
        for (i,btn) in buttonView.subviews.enumerated()
        {
            //按钮大小
            let btnSize = CGSize(width: 100, height: 100)
            //间距
            let margin = (buttonView.width - 3 * btnSize.width)/4.0
//            0  1  2  3  4   5
//            0  1  2  0   1   2
            let col = i%3
            let x: CGFloat = margin + CGFloat(col) * (margin + btnSize.width)
            let y: CGFloat = (i>2) ? (buttonView.height-btnSize.height) : 0
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
        }
    }
}
